/****************************************************
 * 创建人：@author fengxin    
 * 创建时间: 2019/12/12/10:49
 * 项目名称: SpringCodeGen
 * 文件名称: FileUtil.java
 * 文件描述: 文件操作工具
 *
 * All rights Reserved, Designed By 投资交易团队
 * @Copyright:2016-2019
 *
 ********************************************************/
package com.ysstech.codegen.util;

import com.ysstech.codegen.exception.CodeGenerateException;
import kotlin.text.Regex;
import kotlin.text.RegexOption;

import java.io.File;
import java.util.*;

/**
 * 包名称：com.ysstech.plugin.idea.codegen.util
 * 类名称：FileUtil
 * 类描述：文件操作工具
 * 创建人：@author fengxin
 * 创建时间：2019/12/12/10:49
 */
public class FileUtils {

    public static boolean dirExists(String path) {
        File file = new File(path);
        return file.exists() && file.isDirectory();
    }

    public static void makeDir(String path) {
        File file = new File(path);
        if(!file.exists()) {
            if(!file.mkdir()) {
                throw new CodeGenerateException("mkdir "+path+" failed.");
            }
        }
    }

    public static List<File> findAllChildFileDir(File  parent, String childNamePattern) {
        List<File> resultFiles = new ArrayList<>();
        if (!parent.isDirectory()) {
            return  resultFiles;
        }

        File[] subDirs = parent.listFiles(File::isDirectory);

        File[] subFiles = parent.listFiles((dir, name) -> {
            Set<RegexOption> options = new HashSet<>();
            Regex regex = new Regex(childNamePattern,options);
            return  regex.find(name,0)!=null;
        });

        resultFiles.addAll(Arrays.asList(subFiles));

        for (File file: subDirs) {
            resultFiles.addAll(findAllChildFileDir(file, childNamePattern));
        }
        return resultFiles;
    }


}
